package com.auction.service.impl;

import com.auction.common.dao.MyBaseServiceImpl;
import com.auction.common.utils.DateUtil;
import com.auction.entity.Order;
import com.auction.mapper.OrderMapper;
import com.auction.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class OrderServiceImpl extends MyBaseServiceImpl<Order, OrderMapper> implements OrderService {
    @Autowired
    private OrderMapper orderMapper;

    private final String PREFIX = "JPDD";
    private String maxCode = null;

    @Override
    public int deleteOrderById(Integer id) {
        return orderMapper.deleteOrderById(id);
    }

    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    @Override
    public int updateOrderStatus(Order order) {
        return orderMapper.updateOrderStatus(order);
    }

    @Override
    public int addOrder(Order order) {
        String code=generateCode();
        order.setOrder_code(code);
        String delivery_data=order.getDelivery_data();
        if (delivery_data==null||"".equals(delivery_data)){
            order.setDelivery_data(null);
        }
        double shipping_fee=order.getShipping_fee();
        double product_price=order.getProduct_price();
        double order_amount = order.getOrder_amount();
        order_amount=order_amount+shipping_fee;
        order.setOrder_amount(order_amount);
        return orderMapper.addOrder(order);
    }

    /**
     * 生成编码
     * @return
     */
    String generateCode(){
        String date = DateUtil.getYm();
        if(null == maxCode){
            maxCode = orderMapper.maxCode(date);
            if(maxCode==null || "".equals(maxCode)){
                maxCode = PREFIX+date+"001";
                return maxCode;
            }
        }
        String month = maxCode.substring(4,10);
        if(!date.equals(month)){
            maxCode = PREFIX+date+"001";
            return maxCode;
        }
        String num = maxCode.substring(10);
        maxCode = PREFIX+date+String.format("%03d",(Integer.parseInt(num)+1));
        return maxCode;
    }
}
